package com.game.logic.core.scene;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/// 帧服务
@Slf4j
public class FrameService {
    protected  final StateSynchronizer<Integer> stateSynchronizer = new StateSynchronizer<>();

    /// 状态同步线程池
    protected final ScheduledExecutorService syncExecutor = Executors.newSingleThreadScheduledExecutor();

    /// 帧率控制线程池
    protected final ScheduledExecutorService frameScheduler = Executors.newSingleThreadScheduledExecutor();


    /// 目标帧率
    protected static final int TARGET_FPS = 10;

    /// 最高帧
    protected static final long MAX_FPS = 12;


    /// 帧间隔时间 (毫秒) - 使用MAX_FPS来设置调度频率
    protected static final long FRAME_INTERVAL_MS = 1000 / MAX_FPS;

    /// 帧计数器
    protected final AtomicLong frameCounter = new AtomicLong(0);

    /// 上次统计时间
    protected volatile long lastStatsTime = System.currentTimeMillis();

    /// 上一帧时间戳
    protected volatile long lastFrameTime;

    /// 上次统计时的帧数
    protected volatile long lastStatsFrameCount = 0;

    /// 缓存的当前时间戳（减少系统调用）
    protected volatile long cachedCurrentTime = System.currentTimeMillis();

    /// 预分配的日志格式字符串（减少字符串拼接开销）
    protected static final String LOG_FORMAT = "地图帧率统计 - 目标FPS: {}, 最高FPS: {}(帧间隔{}), 平均FPS: {}(帧间隔{}), 帧记录: {}";

    /// 统计间隔常量（避免魔法数字）
    protected static final long STATS_INTERVAL_MS = 1000L;


    public void afterPropertiesSet(String topic) {
        log.info("启动{}帧循环，目标帧率: {}FPS，帧间隔: {} ms", topic, TARGET_FPS, FRAME_INTERVAL_MS);
        frameScheduler.scheduleAtFixedRate(this::mapFrameState, 0, FRAME_INTERVAL_MS, TimeUnit.MILLISECONDS);
    }


    /// 地图帧状态
    protected void mapFrameState() {
        try {
            // 更新缓存时间戳
            cachedCurrentTime = System.currentTimeMillis();

            long frameInterval = cachedCurrentTime - lastFrameTime;
            long currentFrame = frameCounter.incrementAndGet();

            // 执行状态同步
            syncExecutor.execute(() -> {
                try {
                    stateSynchronizer.synchronize();
                } catch (Exception e) {
                    log.error("状态同步错误", e);
                }
            });
            lastFrameTime = cachedCurrentTime;

            // 每5秒统计一次帧率（减少日志I/O开销）
            if (cachedCurrentTime - lastStatsTime >= STATS_INTERVAL_MS) {
                long actualFPS = (currentFrame - lastStatsFrameCount); // 统计间隔内的平均帧数

//                log.debug(LOG_FORMAT, TARGET_FPS, MAX_FPS, FRAME_INTERVAL_MS, actualFPS, frameInterval, currentFrame);

                lastStatsTime = cachedCurrentTime;
                lastStatsFrameCount = currentFrame; // 记录当前帧数用于下次计算
            }

        } catch (Exception e) {
            log.error("地图帧状态处理异常", e);
        }
    }

    protected void stopFrameLoop() {
        frameScheduler.shutdown();
        syncExecutor.shutdown();
        try {
            if (!frameScheduler.awaitTermination(5, TimeUnit.SECONDS)) {
                frameScheduler.shutdownNow();
            }
            if (!syncExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
                syncExecutor.shutdownNow();
            }
        } catch (InterruptedException e) {
            frameScheduler.shutdownNow();
            syncExecutor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}
